package com.spica.spicaschool.initializer

import android.content.Context
import androidx.startup.Initializer
import okhttp3.OkHttpClient
import rxhttp.RxHttpPlugins
import rxhttp.wrapper.cahce.CacheMode
import rxhttp.wrapper.cookie.CookieStore
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.ssl.HttpsUtils
import java.io.File
import java.util.concurrent.TimeUnit

@Suppress("unused")
class RxHttpInitializer : Initializer<Unit> {

    override fun create(context: Context) {
        val sslParams = HttpsUtils.getSslSocketFactory()

        val cacheDir = File(context.externalCacheDir, "HttpCache")
        // 设置缓存
        RxHttpPlugins.setCache(
            cacheDir,
            10 * 1024 * 1024,
            CacheMode.REQUEST_NETWORK_FAILED_READ_CACHE,
            60 * 1000
        )

        val client = OkHttpClient.Builder()
            .cookieJar(CookieStore()) // 支持Cookie
            .retryOnConnectionFailure(true) // 自动重连
            .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager) // 关闭证书校验
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(15, TimeUnit.SECONDS)
            .writeTimeout(15, TimeUnit.MILLISECONDS)
            .build()

        // 完成初始化
        RxHttp.init(client, true)
    }

    override fun dependencies(): List<Class<out Initializer<*>>> = emptyList()
}
